//
//  BSHomeViewController.m
//  BeleireaShop
//
//  Created by imac on 2019/10/22.
//  Copyright © 2019 imac. All rights reserved.
//

#import "THTreeHoleChildCollectViewController.h"
@interface THTreeHoleChildCollectViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
@property(nonatomic, strong) UIView                     *header;/**<  */
@property(nonatomic, strong) NSMutableArray                   *dataSouce;/**<  */
@property(nonatomic, strong) NSMutableArray                   *t_dataSouce;/**<  */
@property(nonatomic, assign) NSInteger                     page;/**<  */
@property(nonatomic, strong) UICollectionView                     *collectionView;
@property(nonatomic, strong) STTools_TagMenuView                     *menuView;/**<  */

@property(nonatomic, strong) NSArray                     *cateArray;/**<  */
@end

@implementation THTreeHoleChildCollectViewController

#pragma mark --vc生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = WH_UICOLOR_FROM_RGBA(0xFBFBFB);
    [self stoneobs_ui_configSubView];
    [self addNotifacations];
    // Do any additional setup after loading the view.
}
#pragma mark --Notifacation
- (void)addNotifacations{
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(viewWillAppear:)
                                                 name:@"update_list_notifi"
                                               object:nil];
    
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (self.didLoad) {
        [self sendVideoListRequest];
        [self sendTieZiListRequest];
        
    }
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
}
#pragma mark --configSubView
- (void)stoneobs_ui_configSubView{
    self.header = [self config_header_view];
    [self.view addSubview:self.header];
    [self.view addSubview:self.collectionView];
    [self.collectionView.mj_header beginRefreshing];
    THTreeHoleHomeViewController * vc = (id)self.parentViewController;
    self.collectionView.frame =  CGRectMake(0, self.header.bottom, UISCREEN_WIDTH, vc.scrollView.height - self.header.bottom);
    self.tableView.frame = self.collectionView.frame;
    self.tableView.contentInset = UIEdgeInsetsZero;
    self.collectionView.hidden = YES;
    
    __weak typeof(self) weakSelf =  self;
    self.tableView.st_noreslutView = [[STTools_NoresultView alloc] initWithFrame:CGRectMake(0, self.tableView.tableHeaderView.height + 30, STONEOBS_UI_UISCREEN_WIDTH, 400) title:@"暂无数据" buttonTitle:@"" buttonHandle:^(NSString *titleString) {
        
    }];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.page = 1;
        [weakSelf sendTieZiListRequest];
    }];
    [self.tableView.mj_header beginRefreshing];
}
- (UIView*)config_header_view{
    UIView * header = [UIView.alloc initWithFrame:CGRectMake(0, 0, UISCREEN_WIDTH, 20)];
    header.backgroundColor = UIColor.whiteColor;
    __weak typeof(self) weakSelf =  self;
    STTools_TagMenuView * menuView = [STTools_TagMenuView.alloc initWithFrame:CGRectMake(10, 0, UISCREEN_WIDTH - 20, 20)];
    menuView.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    menuView.forceButtonHeight = 24;
    menuView.cornerRadius = 12;
    
    menuView.buttonBackGroundColor = UIColor.clearColor;
    menuView.buttonSelctedBackGroundColor = WH_UICOLOR_FROM_RGBA(0xD8FFE5);
    
    menuView.butTitleColor = WH_UICOLOR_FROM_RGBA(0x9A9A9A);
    menuView.butTitleSelectedColor = STONEOBS_UI_THEME_BACKGROUNDCOLOR;
    
    menuView.buttonBoderColor = UIColor.clearColor;
    menuView.buttonSelectedBoderColor = UIColor.clearColor;
    NSArray * array = @[@"图文",@"视频"];
    menuView.allArray = array;
    menuView.chosedArray = @[array.firstObject];
    [menuView setOnSlectedTagView:^(STTools_TagMenuView *tagView, NSString *title, NSInteger index) {
        weakSelf.page = 1;
        if (index == 0) {
            weakSelf.tableView.hidden = NO;
            weakSelf.collectionView.hidden = YES;

        }else{
            weakSelf.collectionView.hidden = NO;
            weakSelf.tableView.hidden = YES;

        }
    }];
    self.menuView = menuView;
    [header addSubview:menuView];
    
    UIView * stoneobs_ui_line = [[UIView alloc] initWithFrame:CGRectMake(0, menuView.bottom, UISCREEN_WIDTH, 10)];
    stoneobs_ui_line.backgroundColor = self.view.backgroundColor;
    [header addSubview:stoneobs_ui_line];
    
    header.height = stoneobs_ui_line.bottom  ;
    

    return header;
    
}
- (UICollectionView *)collectionView{
    if (!_collectionView) {
        UICollectionViewFlowLayout * flow = UICollectionViewFlowLayout.new;
        flow.sectionInset = UIEdgeInsetsMake(0, 15, 15, 15);
        _collectionView = [[UICollectionView alloc] initWithFrame:STONEOBS_UI_UISCREEN_FRAME collectionViewLayout:flow];
        _collectionView.backgroundColor = UIColor.clearColor;
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
        //注册
        __weak typeof(self) weakSelf =  self;
        [_collectionView registerClass:[THTreeHoleVideoCollectionViewCell class] forCellWithReuseIdentifier:@"item"];
        _collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            weakSelf.page = 1;
            [weakSelf sendVideoListRequest];
        }];

        _collectionView.st_noreslutView = [[STTools_NoresultView alloc] initWithFrame:CGRectMake(0, 50, UISCREEN_WIDTH, 400) title:@"暂无数据" buttonTitle:@"" buttonHandle:^(NSString *titleString) {
            
        }];

        self.automaticallyAdjustsScrollViewInsets = NO;
        if (STMC_IOS11) {
            if ([_collectionView respondsToSelector:@selector(setContentInsetAdjustmentBehavior:)]) {
                [_collectionView performSelector:@selector(setContentInsetAdjustmentBehavior:) withObject:@(2) afterDelay:0];
            }
        }else{
            self.automaticallyAdjustsScrollViewInsets = NO;
        }

    }
    return _collectionView;
}
#pragma --mark UICollectionViewDataSource
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.dataSouce.count;
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat witdh =  (UISCREEN_WIDTH - 30 -  15)/2;
    return CGSizeMake(witdh, 300);
}
-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    THTreeHoleVideoCollectionViewCell * item =[collectionView dequeueReusableCellWithReuseIdentifier:@"item" forIndexPath:indexPath];
    item.model = self.dataSouce[indexPath.row];
    item.layer.cornerRadius = 10;
    item.clipsToBounds = YES;
    return item;
}

#pragma --mark UICollectionViewDelegate
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
     THTieZiModel* model = self.dataSouce[indexPath.row];
     [TMUtils goto_tiezi_detail:model dataSouce:self.dataSouce];
    [self.collectionView deselectItemAtIndexPath:indexPath animated:NO];
    
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGFloat content = scrollView.contentOffset.y;
    //    NSLog(@"%0.2f",content);
}

#pragma --mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.t_dataSouce.count ;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    THTieZiModel * model = self.t_dataSouce[indexPath.row];
    if (model.cus_height < 10) {
        [self tableView:tableView cellForRowAtIndexPath:indexPath];
    }
    return model.cus_height;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 0.01;
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * reuseIdentifier =  @"cell";
    THTreeholeTieZiTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (!cell) {
        cell = [[THTreeholeTieZiTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
        
    }
    THTieZiModel * model = self.t_dataSouce[indexPath.row];
    cell.itemView.model = model;
    __weak typeof(self) weakSelf =  self;
    [cell.itemView setOnselctedOpenButton:^(THTieZiModel * _Nonnull model) {
        model.cus_open = YES;
        [weakSelf.tableView reloadData];
    }];
    return cell;
}
#pragma --mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    THTieZiModel* model = self.t_dataSouce[indexPath.row];
    [TMUtils goto_tiezi_detail:model dataSouce:self.dataSouce];
    [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
}
#pragma mark --NetWork Method
- (void)configRefreshFooter{
    __weak typeof(self) weakSelf =  self;
    self.collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        weakSelf.page ++;
        [weakSelf sendVideoListRequest];
    }];
}
- (void)configTieziRefreshFooter{
    __weak typeof(self) weakSelf =  self;
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        weakSelf.page ++;
        [weakSelf sendTieZiListRequest];
    }];
}
- (void)sendTieZiListRequest{
    NSMutableDictionary * stoneobs_net_param_dic = [NSMutableDictionary new];
    NSString * stoneobs_net_user_id = [STTools_UserManger defult].stoneobs_fun_get_loginedUser.uid.description;
    NSString * stoneobs_net_user_token = STTools_UserManger.defult.stoneobs_fun_get_loginedUser.token;
    if (stoneobs_net_user_id.length) {
        [stoneobs_net_param_dic setObject:stoneobs_net_user_id forKey:@"uid"];
    }
    if (stoneobs_net_user_token.length) {
        [stoneobs_net_param_dic setObject:stoneobs_net_user_token forKey:@"token"];
    }

    [stoneobs_net_param_dic setObject:@"1" forKey:@"get_up"];
    [stoneobs_net_param_dic setObject:@"1" forKey:@"type"];
    NSString * stoneobs_net_net_url = [NSString stringWithFormat:@"%@%@",RELEASE_SERVER_URL_HEADER,@"v1/posts/lists"];
    DDLogInfo(@"url:%@",stoneobs_net_net_url);
    DDLogInfo(@"param:%@",stoneobs_net_param_dic);
    [[STTools_NetWrokManger defaultClient] stoneobs_fun_requestWithPath:stoneobs_net_net_url
                                                                 method:STHttpRequestType_stoneobs_enumGet
                                                             parameters:stoneobs_net_param_dic
                                                                success:^(NSURLSessionDataTask *operation, id responseObject) {
        [SVProgressHUD dismiss];
        NSDictionary * dic = [responseObject valueForKey:@"data"];
        NSArray * array = dic[@"items"];
        NSArray * objArray = [THTieZiModel mj_objectArrayWithKeyValuesArray:array];
        NSInteger total = [dic[@"total"] integerValue];//总数量
        CGFloat perPage = [dic[@"perPage"] floatValue];
        CGFloat allpage = total / perPage; ;
        if (self.page == 1) {
            self.t_dataSouce = objArray.mutableCopy;
            [self.tableView reloadData];
            if (allpage>1) {
                [self configTieziRefreshFooter];
            }
        }else{
            if (self.page < allpage) {
                [self.tableView.mj_footer endRefreshing];
            }else{
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
            [self.t_dataSouce addObjectsFromArray:objArray];
           [self.tableView reloadData];
        }
        [self.tableView.mj_header endRefreshing];
        
        DDLogInfo(@"%@请求成功:resp\n%@",stoneobs_net_net_url,responseObject);
        
    } failure:^(NSString *stateCode, STTools_Error *error,NSError *originError) {
        [SVProgressHUD dismiss];
        
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        DDLogError(@"\n请求失败:\nurl:%@\nparam:%@\n失败原因:%@\n错误码:%ld",
                   stoneobs_net_net_url,stoneobs_net_param_dic,error.desc,error.code);
    }];
    
    
    
}
- (void)sendVideoListRequest{
    NSMutableDictionary * stoneobs_net_param_dic = [NSMutableDictionary new];
    NSString * stoneobs_net_user_id = [STTools_UserManger defult].stoneobs_fun_get_loginedUser.uid.description;
    NSString * stoneobs_net_user_token = STTools_UserManger.defult.stoneobs_fun_get_loginedUser.token;
    if (stoneobs_net_user_id.length) {
        [stoneobs_net_param_dic setObject:stoneobs_net_user_id forKey:@"uid"];
    }
    if (stoneobs_net_user_token.length) {
        [stoneobs_net_param_dic setObject:stoneobs_net_user_token forKey:@"token"];
    }
    [stoneobs_net_param_dic setObject:@"1" forKey:@"get_up"];
    [stoneobs_net_param_dic setObject:@"2" forKey:@"type"];
    NSString * stoneobs_net_net_url = [NSString stringWithFormat:@"%@%@",RELEASE_SERVER_URL_HEADER,@"v1/posts/lists"];
    DDLogInfo(@"url:%@",stoneobs_net_net_url);
    DDLogInfo(@"param:%@",stoneobs_net_param_dic);
    [[STTools_NetWrokManger defaultClient] stoneobs_fun_requestWithPath:stoneobs_net_net_url
                                                                 method:STHttpRequestType_stoneobs_enumGet
                                                             parameters:stoneobs_net_param_dic
                                                                success:^(NSURLSessionDataTask *operation, id responseObject) {
        [SVProgressHUD dismiss];
        NSDictionary * dic = [responseObject valueForKey:@"data"];
        NSArray * array = dic[@"items"];
        NSArray * objArray = [THTieZiModel mj_objectArrayWithKeyValuesArray:array];
        NSInteger total = [dic[@"total"] integerValue];//总数量
        CGFloat perPage = [dic[@"perPage"] floatValue];
        CGFloat allpage = total / perPage; ;
        if (self.page == 1) {
            self.dataSouce = objArray.mutableCopy;
            [self.collectionView reloadData];
            if (allpage>1) {
                [self configRefreshFooter];
            }
        }else{
            if (self.page < allpage) {
                [self.collectionView.mj_footer endRefreshing];
            }else{
                [self.collectionView.mj_footer endRefreshingWithNoMoreData];
            }
            [self.dataSouce addObjectsFromArray:objArray];
            [self.collectionView reloadData];
        }
        [self.collectionView.mj_header endRefreshing];
        
        DDLogInfo(@"%@请求成功:resp\n%@",stoneobs_net_net_url,responseObject);
        
    } failure:^(NSString *stateCode, STTools_Error *error,NSError *originError) {
        [SVProgressHUD dismiss];
        
        [self.collectionView.mj_header endRefreshing];
        [self.collectionView.mj_footer endRefreshing];
        DDLogError(@"\n请求失败:\nurl:%@\nparam:%@\n失败原因:%@\n错误码:%ld",
                   stoneobs_net_net_url,stoneobs_net_param_dic,error.desc,error.code);
    }];
    
    
    
}
@end
